﻿/****************
 * xml操作类，通过一个xml操作类更改
 * ***************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Data;
using System.Xml.Linq;
using VideoFlowStatistics.EntityClass;

namespace VideoFlowStatistics.Class
{
    class XmlHelper
    {
        static string Xpath = System.Windows.Forms.Application.StartupPath.EndsWith("\\") ? System.Windows.Forms.Application.StartupPath
                                + "Data.Xml" : System.Windows.Forms.Application.StartupPath + "\\Data.Xml";
        static string node = "Rows";

        static XmlHelper()
        {
            if (!File.Exists(Xpath))
            {
                //XmlDocument xmlDoc = new XmlDocument();
                ////建立Xml的定义声明
                //XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "GB2312", null);
                //xmlDoc.AppendChild(dec);
                ////创建根节点
                //XmlElement root = xmlDoc.CreateElement("Docs");
                //xmlDoc.AppendChild(root);
                //xmlDoc.Save(Xpath);
                XDocument xmldoc = new XDocument(
                        new XElement(node)
                    );
                xmldoc.Save(Xpath);
            }
        }

        ///// <summary>
        ///// 获取
        ///// </summary>
        ///// <returns></returns>
        //public static DataTable Read()
        //{
        //    DataSet ds = new DataSet();
        //    XmlDataDocument doc = new XmlDataDocument();
        //    doc.Load(Xpath);
        //    XmlNodeReader cmlnode = new XmlNodeReader(doc);

        //    ds.ReadXml(cmlnode);

        //    if (ds != null && ds.Tables.Count > 0)
        //    {
        //        return ds.Tables[0];
        //    }

        //    return new DataTable();
        //}

        public static IList<SearchList> Read(DateTime stateTime, DateTime endTime)
        {
            XElement xelment = XElement.Load(Xpath);
            var xelments = from xe in xelment.Elements("Row")
                           where DateTime.Parse(xe.Element("Time").Value).AddDays(1) >= stateTime && DateTime.Parse(xe.Element("Time").Value.ToString()) < endTime
                           orderby xe.Element("Time").Value descending
                           select new SearchList
                           {
                               Time = xe.Element("Time").Value.ToString(),
                               Count = xe.Element("Count").Value.ToString()
                           };
            //var test = 
            return xelments.ToList(); ;
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="node">根节点</param>
        /// <param name="elementTime">第一个属性</param>
        /// <param name="elementCount">第二个属性</param>
        /// <param name="valueTime">第一个属性值</param>
        /// <param name="valueCount">第二个属性值</param>
        public static void Insert(string elementTime, string elementCount, string valueTime, string valueCount)
        {
            try
            {
                XElement xelment = XElement.Load(Xpath);

                XElement rows = new XElement("Row",
                      new XElement(elementTime, valueTime),
                       new XElement(elementCount, valueCount)
                    );
                xelment.Add(rows);
                xelment.Save(Xpath);
            }
            catch { }
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="node">根节点</param>
        /// <param name="elementTime">第一个属性</param>
        /// <param name="elementCount">第二个属性</param>
        /// <param name="valueTime">第一个属性值</param>
        /// <param name="valueCount">第二个属性值</param>
        public static void Insert(string root, string elementTime, string elementCount, string valueTime, string valueCount)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Xpath);
            XmlNode xn = doc.SelectSingleNode(root);
            XmlElement rows = doc.CreateElement("Row");
            XmlElement elementtime = doc.CreateElement(elementTime);
            elementtime.InnerText = valueTime;
            rows.AppendChild(elementtime);
            XmlElement elementcount = doc.CreateElement(elementCount);
            elementcount.InnerText = valueCount;
            rows.AppendChild(elementcount);
            xn.AppendChild(rows);
        }

        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名，非空时修改该节点属性值，否则修改节点值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.Insert(path, "/Node", "", "Value")
         * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
         ************************************************/
        public static void Update(string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Xpath);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xe.InnerText = value;
                else
                    xe.SetAttribute(attribute, value);
                doc.Save(Xpath);
            }
            catch { }
        }
    }


    /// <summary>
    /// txt文件操作类
    /// </summary>
    class txtControl
    {
        static string txtPath = System.Windows.Forms.Application.StartupPath.EndsWith("\\") ? System.Windows.Forms.Application.StartupPath
                                + "Data.Xml" : System.Windows.Forms.Application.StartupPath + "\\MatrixH.txt";

        public static void Insert(List<float[]> list)
        {
            string strH = string.Empty;
            foreach (var item in list)
            {
                foreach (float itemf in item)
                {
                    strH += itemf + ",";
                }
                strH += Environment.NewLine;
            }
            if (!File.Exists(txtPath))
            {
                File.CreateText(txtPath);
            }
            StreamWriter strW = new StreamWriter(txtPath, false, Encoding.UTF8);
            strW.WriteLine(strH);
            strW.Close();
        }

        public static void Read()
        {
            List<string[]> list = new List<string[]>();
            if (!File.Exists(txtPath)) return;
            StreamReader strR = new StreamReader(txtPath, Encoding.UTF8);
            string MatrixH = string.Empty;
            string[] strList = System.Text.RegularExpressions.Regex.Split(strR.ReadToEnd(), Environment.NewLine);
            strR.Close();
            foreach (var item in strList)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    // list.Add(Array.ConvertAll<string, float>(item.Split(','), Convert.ToSingle)); 
                    list.Add(item.Split(','));
                }
            }
            //将每组数据的每列数据计算平均数
            for (int i = 0; i < strList[0].Split(',').Length-1; i++)
            {
                float[] flist = Array.ConvertAll<string, float>(list.Select(l => l[i]).ToArray(), Convert.ToSingle);
                float fl = flist.Average();
                MatrixH += fl + ",";
            }
            Properties.Settings.Default.MatrixH = MatrixH;
            Properties.Settings.Default.Save();
        }
    }
}
